package leetcode

import (
	"sort"
	"strconv")


func displayTable(orders [][]string) [][]string {
	// 餐品字典序排序
	foodMap := make(map[string]int)
	foodSlice := []string{}
	tableMap := make(map[string]int)
	tableSlice := []int{}

	for _, order := range orders {
		if foodMap[order[2]] == 0 {
			foodMap[order[2]] = 1
			foodSlice = append(foodSlice, order[2])
		}

		if tableMap[order[1]] == 0 {
			tableMap[order[1]] = 1
			intOrder, _ := strconv.Atoi(order[1])
			tableSlice = append(tableSlice, intOrder)
		}
	}

	sort.Strings(foodSlice)
	sort.Ints(tableSlice)

	// 形成foodList
	foodIndex := 1
	foodList := make(map[string]int)
	for _, food := range foodSlice {
		if foodList[food] == 0 {
			foodList[food] = foodIndex
			foodIndex++
		}
	}

	// 形成tableList
	tableIndex := 1
	tableList := make(map[string]int)
	for _, table := range tableSlice {
		strTable := strconv.Itoa(table)
		if tableList[strTable] == 0 {
			tableList[strTable] = tableIndex
			tableIndex++
		}
	}

	//fmt.Println(tableList)

	// 整理数据，形成tables
	tables := make([][]int, tableIndex)
	for i := range tables {
		tables[i] = make([]int, foodIndex)
	}
	for _, order := range orders {
		table := tableList[order[1]]
		food := foodList[order[2]]
		tables[table][food] += 1
	}

	//fmt.Println(tables)

	// 整理成返回值
	ans := make([][]string, tableIndex)
	for i := range ans {
		ans[i] = make([]string, foodIndex)
	}

	// food
	ans[0][0] = "Table"
	index := 1
	for _, food := range foodSlice {
		ans[0][index] = food
		index++
	}

	// table
	index = 1
	for _, table := range tableSlice {
		strTable := strconv.Itoa(table)
		ans[index][0] = strTable
		index++
	}

	// tables
	for i := 1; i < tableIndex; i++ {
		for j := 1; j < foodIndex; j++ {
			ans[i][j] = strconv.Itoa(tables[i][j])
		}
	}

	return ans
}